﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace Kokomo
{
	public class MethodBasedTypeConverter<TSource, TTarget> : TypeConverter
	{
		public MethodBasedTypeConverter(Func<TSource, TTarget> converter, Func<TTarget, TSource> inverseConverter)
		{
			this.Converter = converter;
			this.InverseConverter = inverseConverter;
		}

		public Func<TSource, TTarget> Converter { get; private set; }
		public Func<TTarget, TSource> InverseConverter { get; private set; }

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			bool canConvert;
			//bool canConvert=base.CanConvertFrom(context, sourceType);
			//if (!canConvert)
			{
				canConvert = (sourceType == typeof(TSource)) && (this.Converter != null);
			}

			return canConvert;
		}
		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			bool canConvert;
			//bool canConvert = base.CanConvertTo(context, destinationType);
			//if (!canConvert)
			{
				canConvert = (destinationType == typeof(TTarget)) && (this.InverseConverter != null);
			}

			return canConvert;
		}

		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			object converted = this.Converter((TSource)value);
			return converted;
		}
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			object converted = this.InverseConverter((TTarget)value);
			return converted;
		}
	}
}
